package com.yinxing.webapi.code.controller.sys;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.yinxing.framework.domain.R;
import com.yinxing.webapi.code.entity.sys.SysMessage;
import com.yinxing.webapi.code.entity.sys.SysMessageQuery;
import com.yinxing.webapi.code.service.sys.ISysMessageService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.Map;

@RestController
@RequestMapping("/SysMessageController")
public class SysMessageController {

    @Autowired
    private ISysMessageService service;

    /**
     * 分页查询
     * @param page 分页模型(url?page=1&limit=20)
     * @param params 查询参数 url?page=1&limit=20&key1=value1&key2=value2
     */
    @GetMapping("/selectPage")
    public R selectPage(Page<SysMessage> page, @RequestParam Map<String,String> params) {
        QueryWrapper<SysMessage> qw = new QueryWrapper<>();

        //条件查询
        if(params.containsKey("treeNodeId")) {
            //由于SQL使用了连表查询，所以查询条件要带入别名.
            qw.eq("msg.SysDicId_", params.get("treeNodeId"));
        }

        //已读未读
        if(params.containsKey("IsRead_")) {
            String readVal = params.get("IsRead_");
            if("read".equals(readVal)) {
                qw.eq("msg.IsRead_", true);
            }
            if("unread".equals(readVal)) {
                qw.eq("msg.IsRead_", false);
            }
        }

        //时间范围
        if(params.containsKey("TimeBegin_")) {
            qw.ge("Date(msg.CreateTime_)", params.get("TimeBegin_"));
        }
        if(params.containsKey("TimeEnd_")) {
            qw.le("Date(msg.CreateTime_)", params.get("TimeEnd_"));
        }
        qw.orderByDesc("msg.Id_");

        IPage<SysMessageQuery> iPage = service.selectMyPageList(page, qw);
        return R.ok(iPage);
    }

    /**
     * 主键删除
     * @param id 主键
     */
    @PostMapping("/deleteById")
    public R deleteById(@RequestParam Long id) {
        service.deleteByIdAndPush(id);
        return R.ok();
    }

    /**
     * 主键批量删除
     * @param ids 主键
    */
    @PostMapping("/deleteBatchById")
    public R deleteBatchById(@RequestParam Long[] ids) {
        service.deleteBatchByIdAndPush(ids);
        return R.ok();
    }

    /**
     * 主键查询
     * @param id 主键
     */
    @GetMapping("/selectById")
    public R selectById(@RequestParam Long id) throws Exception {
        SysMessage record = service.selectDetailById(id);
        return R.ok(record);
    }

    /**
     * 新增
     * @param record 实体类
     */
    @PostMapping("/insert")
    public R insert(SysMessage record) {
        service.insertMessage(record);
        return R.ok();
    }
}
